import CURDHelper from '@/utils/CURDHelper'
import PageConfig from '@/utils/pageConfig'
import { getBtnCtr } from '@/utils/BtnControl'
import Query from '@/components/Query';
import { isNumber } from '@/utils/validate';
import { VxeUI } from 'vxe-pc-ui';
import XEUtils from 'xe-utils';
import XLSX from 'xlsx';
export default {
  name: 'BaseProduct',
  components: {
    Query
  },
  data() {
    return {
      componentSize: PageConfig.ComponentSize,
      duration: PageConfig.Duration,
      btnPromission: '',
      editModal: false,
      QueryConditions: [],
      BaseApiUrl:'/api/Xmjcgltx',
      importModal:false,
      QueryConfig: [{
        title: '体系名称',
        field: 'txmc',
        type: 'input',
        value: '',
        placeholder: '请输入体系名称以查询',
      }, {
        title: '体系规格',
        field: 'txgg',
        type: 'input',
        value: '',
        placeholder: '请输入体系规格以查询',
      }
      ],
      GridOptions: {
        id: 'BaseProduct_MainGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 700,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        exportConfig: {
        },
        toolbarConfig: {
          custom: true,
          export: true,
          slots: {
            buttons: 'customButtons'
          }
        },
        customConfig: {
          mode: 'drawer',
          storage: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'txbm', title: '体系编码', sortable: true, minWidth: 100, showOverflow: true },
          { field: 'txmc', title: '体系名称', sortable: true, minWidth: 150, showOverflow: true },
          { field: 'txgg', title: '体系规格', sortable: true, minWidth: 100, showOverflow: true },
          //{ field: 'txjg', title: '体系价格', sortable: true, minWidth: 50, showOverflow: true },
          { field: 'rzzq', title: '认证周期(年)', minWidth: 80 },
          { field: 'rztxzq', title: '认证提醒(天)', minWidth: 80 },
          { field: 'jszq', title: '监审周期(年)', minWidth: 80 },
          { field: 'jstxzq', title: '监审提醒(天)', minWidth: 80 },
          { field: 'rzbz', title: '认证标准', minWidth: 100, showOverflow: true },
          { field: 'bz', title: '备注', minWidth: 100, showOverflow: true },
          { field: 'createtime', title: '创建时间', minWidth: 150, showOverflow: true },
          { field: 'createname', title: '创建人', minWidth: 100, showOverflow: true },
          { field: 'updatetime', title: '更新时间', minWidth: 150, showOverflow: true },
          { field: 'updatename', title: '更新人', minWidth: 100, showOverflow: true },
          { field: 'operation', title: '操作', fixed: 'right', width: 120, slots: { default: 'operation' } },
        ],
        data: []
      },
      PagerConfig: {
        align: 'center',
        pageSize: 25,
        total: 0,
        currentPage: 1,
        pageSizes: [10, 25, 50, 100, 200],
      },
      FormOptions: {
        'title-width': 140,
        border: true,
        titleBackground: true,
        data: {
          id: -1,
          createid: '',
          createtime: '',
          createname: '',
          updateid: '',
          updatetime: '',
          updatename: '',
          txjg: 0,
          rzzq: '',
          rztxzq: '',
          txbm: '',
          txmc: '',
          txgg: '',
          jszq: '',
          jstxzq: '',
          tzbz: '',
          bz: '',
        },
        rules: {
          txbm: [{ required: true, message: '请输入体系编码', trigger: 'blur' }],
          txmc: [{ required: true, message: '请输入体系名称', trigger: 'blur' }],
          rzzq: [{ required: true, message: '请输入认证周期(年)）', trigger: 'blur', validator: this.ValidatorNumber }],
          rztxzq: [{ required: true, message: '请输入认证提醒(天)', trigger: 'blur', validator: this.ValidatorNumber }],
          txgg: [{ required: true, message: '请输入体系规格', trigger: 'blur' }],
          jszq: [{ required: true, message: '请输入监审周期(年)）', trigger: 'blur', validator: this.ValidatorNumber }],
          jstxzq: [{ required: true, message: '请输入监审提醒(天)', trigger: 'blur', validator: this.ValidatorNumber }],
          txjg: [{ validator: this.ValidatorNumber }],
          rzbz: [{ required: true, message: '请输入认证标准', trigger: 'blur' }],
        },
        items: [
          { field: 'txbm', title: '体系编码', span: 12, itemRender: { name: 'VxeInput' ,props : {readonly:true} } },
          { field: 'txmc', title: '体系名称', span: 12, itemRender: { name: 'VxeInput' ,props:{ placeholder: '请输入体系名称' }}},
          { field: 'txgg', title: '体系规格', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入体系规格' },
          // { field: 'txjg', title: '体系价格', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入体系价格' },
          { field: 'rzzq', title: '认证周期(年)）', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入认证周期(年)）' },
          { field: 'rztxzq', title: '认证提醒(天)', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入认证提醒(天)' },
          { field: 'jszq', title: '监审周期(年)）', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入监审周期(年)）' },
          { field: 'jstxzq', title: '监审提醒(天)', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入监审提醒(天)' },
          { field: 'rzbz', title: '认证标准', span: 12, itemRender: { name: 'VxeInput' }, placeholder: '请输入认证标准' },
          { field: 'bz', title: '备注', span: 24, itemRender: { name: 'VxeTextarea', maxlegnth: 500, clearable: true, showWordCount: true }, placeholder: '请输入备注' },
          {
            align: 'center',
            span: 24,
            itemRender: {
              name: 'VxeButtonGroup',
              options: [{
                type: 'submit', content: '提交', status: 'primary'
              }, {
                type: 'reset', content: '重置'
              }]
            }
          }
        ]
      },
      ImportGridOptions: {
        id: 'BaseProduct_ImportGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 350,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent: true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'txbm', title: '体系编码', sortable: true, minWidth: 120, showOverflow: true },
          { field: 'txmc', title: '体系名称', sortable: true, minWidth: 120, showOverflow: true },
          { field: 'txgg', title: '体系规格', minWidth: 100, showOverflow: true },
          { field: 'rzzq', title: '认证周期(年)', minWidth: 120, showOverflow: true },
          { field: 'rztxzq', title: '认证提醒(天)', minWidth: 100, showOverflow: true },
          { field: 'jszq', title: '监审周期(年)', minWidth: 120, showOverflow: true },
          { field: 'jstxzq', title: '监审提醒(天)', minWidth: 100, showOverflow: true },
          { field: 'rzbz', title: '认证标准', minWidth: 100, showOverflow: true },
          { field: 'bz', title: '备注', minWidth: 80, showOverflow: true },
        ],
        data: []
      },
    }
  },
  created() {
    // 动态头部按钮
    this.btnPromission = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
  },
  methods: {
    ValidatorNumber(e) {
      if(!e.itemValue){
        return;
      }
      if (!isNumber(e.itemValue)) {
        return new Error('请输入数字');
      } else {
        if (e.itemValue < 0) {
          return new Error('请输入大于等于0的数字');
        }
      }
    },
    handleQuery(e) {
      this.QueryConditions = e;
      this.DoQuery(e);
    },
    handlePageChange() {
      this.DoQuery(this.QueryConditions);
    },
    handleBatchDelete() {
      let rows = this.$refs.maingrid.getCheckboxRecords(true);
      this.DoBatchDelete(rows);
    },
    handleAdd() {
      this.FormOptions.data ={
        id: -1,
        createid: '',
        createtime: '',
        createname: '',
        updateid: '',
        updatetime: '',
        updatename: '',
        txjg: 0,
        rzzq: '',
        rztxzq: '',
        txbm: 'txbm0001',
        txmc: '',
        txgg: '',
        jszq: '',
        jstxzq: '',
        tzbz: '',
        bz: '',
      }
      this.editModal = true;
    },
    handleEdit(row) {
      this.FormOptions.data = row;
      this.editModal = true;
    },
    handleDelete(row) {
      this.DoDelete(row);
    },
    handleEditModalSubmit() {
      this.FormOptions.data.id == -1 ? this.DoAdd() : this.DoEdit();
    },
    handleEditModalReset() {

    },
    handleImport() {
      this.DoImport();
    },
    handleImprotConfirm(){
      this.DoImportConfirm();
    },
    DoQuery(e) {
      let request = {
        isPaging: true,
        pageSize: this.PagerConfig.pageSize,
        pageIndex: this.PagerConfig.currentPage,
        queryConditions: e,
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/Xmjcgltx')
        .then(res => {

          this.GridOptions.data = res.data;
          this.PagerConfig.total = res.totalNumber;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoAdd() {
      //新增
      CURDHelper.Add(this.FormOptions.data, null, '/api/Xmjcgltx')
        .then(res => {
          VxeUI.modal.message({
            content: '新增数据成功',
            status: 'success',
            duration: this.duration
          });          
          this.FormOptions.data.id = -1;
          this.editModal = false;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoEdit() {
      //编辑
      CURDHelper.EditWithConfirm('是否修改当前数据', this.FormOptions.data, null, '/api/Xmjcgltx')
        .then(res => {
          VxeUI.modal.message({
            content: '编辑数据成功',
            status: 'success',
            duration: this.duration
          })
          this.FormOptions.reset();
          this.FormOptions.data.id = -1;
          this.editModal = false;
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoDelete(row) {
      //删除
      let deleteModel = {
        ID: row.id,
        DeleteRemark: ''
      };
      CURDHelper.DeleteWithConfirm('是否删除当前数据', deleteModel, null, '/api/Xmjcgltx')
        .then(res => {
          VxeUI.modal.message({
            content: '删除数据成功',
            status: 'success',
            duration: this.duration
          })
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoBatchDelete(rows) {
      //删除
      let deleteList = [];
      rows.forEach(row => {
        deleteList.push({
          ID: row.id,
          DeleteRemark: ''
        })
      })
      CURDHelper.DeleteWithConfirm('是否删除当前已选择数据，删除后不能恢复', null, deleteList, '/api/Xmjcgltx')
        .then(res => {
          VxeUI.modal.message({
            content: '删除数据成功',
            status: 'success',
            duration: this.duration
          })
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({
            content: err,
            status: 'error',
            duration: this.duration
          })
        })
    },
    DoImport() {
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()
        this.ImportGridOptions.data = [];
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet);
          resultJosn.forEach(item => {
            if (!item['体系编码'] || !item['体系名称'] || !item['体系规格'] || !item['认证周期(年)']
              || !item['认证提醒(天)'] || !item['监审周期(年)'] || !item['监审提醒(天)'] || !item['认证标准']) {
              return;
            }
            let newRow = {
              txbm: item['体系编码'],
              txmc: item['体系名称'].trim(),
              txgg: item['体系规格'].trim(),
              rzzq: item['认证周期(年)'],
              rztxqz: item['认证提醒(天)'],
              jszq: item['监审周期(年)'],
              jstxzq: item['监审提醒(天)'],
              rzbz: item['认证标准'].trim(),
              bz:item["备注"]
            }
            this.ImportGridOptions.data.push(newRow);
          })
          this.importModal = true;
        }
        reader.readAsArrayBuffer(e.file);
      })
    },
    DoImportConfirm(){
      let postList = this.$refs.importModalGrid.getCheckboxRecords(true) ;
      if(!postList || postList.length < 1){
        postList = this.ImportGridOptions.data;
      }
      CURDHelper.Add(null,postList, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({content: '导入数据成功',status: 'success',duration: this.duration});          
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
  }
}
